import React, { useRef, useState } from 'react';
import { Button } from '../UI';
import { validateFile } from '../../utils';

interface FileUploadProps {
  onFileSelect: (file: File) => void;
  disabled?: boolean;
  accept?: string;
  maxSize?: number; // bytes
  className?: string;
}

export function FileUpload({
  onFileSelect,
  disabled = false,
  accept = '*/*',
  maxSize = 10 * 1024 * 1024, // 10MB
  className = '',
}: FileUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragOver, setIsDragOver] = useState(false);
  const [error, setError] = useState('');
  
  const handleFileSelect = React.useCallback((file: File) => {
    setError('');
    
    const validation = validateFile(file, maxSize);
    if (!validation.valid) {
      setError(validation.error || '文件验证失败');
      return;
    }
    
    onFileSelect(file);
  }, [maxSize, onFileSelect]);
  
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
    // 清空input值，允许重复选择同一文件
    e.target.value = '';
  };
  
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    if (!disabled) {
      setIsDragOver(true);
    }
  };
  
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    
    if (disabled) return;
    
    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0) {
      handleFileSelect(files[0]);
    }
  };
  
  const handlePaste = React.useCallback((e: ClipboardEvent) => {
    if (disabled) return;
    
    const items = Array.from(e.clipboardData?.items || []);
    const fileItem = items.find(item => item.kind === 'file');
    
    if (fileItem) {
      const file = fileItem.getAsFile();
      if (file) {
        handleFileSelect(file);
      }
    }
  }, [disabled, handleFileSelect]);
  
  // 监听粘贴事件
  React.useEffect(() => {
    document.addEventListener('paste', handlePaste);
    return () => {
      document.removeEventListener('paste', handlePaste);
    };
  }, [handlePaste]);
  
  return (
    <div className={className}>
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        onChange={handleFileInputChange}
        className="hidden"
        disabled={disabled}
      />
      
      {/* 拖拽区域 */}
      <div
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        className={`border-2 border-dashed rounded-lg p-6 text-center transition-colors ${
          isDragOver
            ? 'border-blue-500 bg-blue-50'
            : 'border-gray-300 hover:border-gray-400'
        } ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
        onClick={() => !disabled && fileInputRef.current?.click()}
      >
        <div className="flex flex-col items-center space-y-2">
          <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
          </svg>
          <div>
            <p className="text-sm font-medium text-gray-900">
              {isDragOver ? '释放文件' : '点击选择文件或拖拽到此处'}
            </p>
            <p className="text-xs text-gray-500 mt-1">
              支持粘贴图片 • 最大 {Math.round(maxSize / 1024 / 1024)}MB
            </p>
          </div>
        </div>
      </div>
      
      {/* 快捷按钮 */}
      <div className="flex space-x-2 mt-3">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => !disabled && fileInputRef.current?.click()}
          disabled={disabled}
          className="flex-1"
        >
          📎 选择文件
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => {
            if (!disabled) {
              const input = document.createElement('input');
              input.type = 'file';
              input.accept = 'image/*';
              input.onchange = (e) => {
                const file = (e.target as HTMLInputElement).files?.[0];
                if (file) handleFileSelect(file);
              };
              input.click();
            }
          }}
          disabled={disabled}
          className="flex-1"
        >
          🖼️ 选择图片
        </Button>
      </div>
      
      {/* 错误提示 */}
      {error && (
        <p className="text-sm text-red-600 mt-2">{error}</p>
      )}
    </div>
  );
}